package com.liuc.practice.bank.transfer.configuration;

import com.liuc.practice.bank.transfer.io.Resource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @Author Liu Chang
 * @Date 2021/2/24 4:40 下午
 */
public class Configuration {

    private static InputStream inputStream = Resource.getResourcesAsInputStream("bean.xml");
    private static Element rootElement;

    static {
        Document read = null;
        try {
            read = new SAXReader().read(inputStream);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        rootElement = read.getRootElement();
    }

    /**
     * 该方法是解析 xml 文件中没有依赖关系的 beans
     **/
    public static Properties parseIndependentBean() {
        Properties properties = new Properties();

        List<Element> nodes = rootElement.selectNodes("//bean");

        for (Element node : nodes) {
            String id = node.attributeValue("id");
            String className = node.attributeValue("className");
            properties.put(id, className);
        }

        return properties;
    }

    /**
     * 将返回值
     */
    public static Map<String, Object> setDependentObject(Map<String, Object> map) throws InvocationTargetException, IllegalAccessException {

        // 被依赖对象
        List<Element> propertyList = rootElement.selectNodes("//property");
        for (Element element : propertyList) {
            Element elementParent = element.getParent();
            String parentId = elementParent.attributeValue("id");
            Object parentObject = map.get(parentId);
            Method[] methods = parentObject.getClass().getMethods();

            String name = element.attributeValue("name");
            String ref = element.attributeValue("ref");
            for (Method method : methods) {
                if (method.getName().equalsIgnoreCase("set" + name)) {
                    method.invoke(parentObject, map.get(ref));
                }
            }

            map.put(parentId, parentObject);
        }


        return map;
    }
}
